var t, e = function(t) {
    return t && t.__esModule ? t : {
      default: t
    };
  },
  a = getApp(),
  o = 0;
var util = require("../../../../utils/util.js")
Page({
  data: {
    data_arr: [],
    listFlag: !1,
    news_input_val: '',
    disableFlag: !1,
    show: !0,
    hide: !1,
    setintervalFunction: "",
    ClickRseply: !0,
    ClickRseply1: !1,
    tempFilePaths: "",
    imgBoo: !0,
    upFlag: !1,
    oppositeList: [],
    imgUrlArr: [],
    imgUrl: [],
    loadingBoo: !0,
    moreBoo: !0,
    currentResult: 0,
    scrollTop: 1e3,
    height: 40,
    oldHeight: 40,
    msgIdArr: [],
    seqIdArr: [],
    centendata: [],
    record_text: "按住 说话",
    recordFlag: !1,
    backoutFlag: !0,
    // 模拟的个人信息数据
    contactList: [{
      patientSimpleVo: {
        userIcon: '/assets/images/head.png',
        name: '小米',
        nmGender: 1,
        age: 30
      },
      dpMedOrderVo: {
        msgTxt: '十万个冷笑话',
        msgPicSmall: ['/assets/images/head.png', '/assets/images/head.png'],
        sessionDateBegin: '2018-10-22-15:06'
      }
    }],
    // 提示消息
    oppositeList: [{
        from: 1,
        parting: 1,
        ctime: '小花',
        msgType: 'SINGLE_VIDEO',
        msg: '你好',
        playFlag: '',
        duration: '哈哈'
      },
      {
        from: 1,
        parting: 1,
        ctime: '小花',
        msgType: 'SINGLE_TEXT',
        msg: '你好',
        playFlag: '呵呵哒',
        duration: '哈哈'
      },
      {
        from: 1,
        parting: 1,
        ctime: '小花',
        msgType: 'SINGLE_VIDEO',
        msg: '你好',
        playFlag: '呵呵哒',
        duration: '哈哈'
      },
      {
        from: 1,
        parting: 1,
        ctime: '小花',
        msgType: 'SINGLE_IMAGE',
        msg: '你好',
        playFlag: '呵呵哒',
        duration: '哈哈'
      }
    ]
  },
  // 获取hei的id节点然后屏幕焦点调转到这个节点  
  bottom: function() {
    var that = this;
    var query = wx.createSelectorQuery()
    query.select('#hei').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function(res) {
      that.setData({
        scrollTop: res[0].height
      })
    })
  },
  toRecord: function(t) {
    var that = this
    var if_over = that.data.if_over
    if (if_over == 1) {
      wx.showToast({
        title: '当前会话已结束',
        icon: 'none',
        duration: 2e3
      })
    } else {
      this.setData({
        recordFlag: !this.data.recordFlag
      });
    }

  },
  getRecord: function() {
    var t = this;
    s ? (s.start(i), this.data.flagBoo = !1, this.data.recordBoo && wx.showModal({
      title: "提示",
      content: "您暂未授权录音功能，请打开右上角 -> 关于 -> 右上角 -> 设置中授权录音功能",
      showCancel: !1,
      confirmColor: "#3b4ca9",
      confirmText: "我知道了"
    }), this.data.recordBooTwo && wx.getSetting({
      success: function(e) {
        console.log(e), 0 == e.authSetting["scope.record"] && (wx.showModal({
          title: "提示",
          content: "您暂未授权录音功能，请打开右上角 -> 关于 -> 右上角 -> 设置中授权录音功能",
          showCancel: !1,
          confirmColor: "#3b4ca9",
          confirmText: "我知道了"
        }), t.setData({
          recordBoo: !0,
          recordBooTwo: !1
        }));
      }
    })) : wx.showModal({
      content: "您当前微信版本过低，暂不支持语音功能，请更新微信版本后重试",
      showCancel: !1,
      confirmColor: "#3b4ca9",
      confirmText: "我知道了"
    });
  },
  shopRecord: function() {
    s && (this.data.flagBoo = !0, s.stop());
  },
  scrollS: function(t) {
    var a = this;
    a.setData({
      tempFilePaths: ""
    });
  },
  bindlinechange: function(t) {
    console.log(t);
    var e = this;
    if (wx.createSelectorQuery) {
      var a = wx.createSelectorQuery();
      a.select("#textarea_bottom").boundingClientRect(), a.exec(function(t) {
        console.log(t), e.setData({
          text_padding: t[0].height,
          scrollTop: e.data.scrollTop + 100
        });
      });
    }
    t.detail.lineCount >= 5 ? this.setData({
      heightFlag: !1
    }) : this.setData({
      heightFlag: !0
    });
  },
  Clickshow: function(t) {
    this.setData({
      show: !0,
      hide: !1
    });
  },
  Clickshow1: function(t) {
    this.setData({
      show: !1,
      hide: !0
    });
  },
  ClickRseply: function(t) {
    this.setData({
      ClickRseply: !1,
      ClickRseply1: !0
    });
  },
  lookPaint: function() {
    var t = this;
    wx.showModal({
      title: "温馨提示",
      content: "您未有查看权限，需患者授权~",
      confirmColor: "#3b4ca9"
    })
  },
  bigImage: function(t) {
    var e = this;
    var imgs = []
    var current = t.currentTarget.dataset.src;
    imgs.push(current)
    //预览图片
    wx.previewImage({
      current: current,
      urls: imgs,
    });
  },
  previewImage: function(t) {
    var e = this.data.contactList.dpMedOrderVo.msgPicBig,
      o = t.target.dataset.imgindex;
    a.previewImage(t, e, o);
  },
  onLoad: function(options) {
    // 提示框
    var that = this;
    var uniacid = a.siteInfo.uniacid
    var userInfo = wx.getStorageSync('userInfo')
    var openid = wx.getStorageSync('openid')
    var touxiang1 = options.touxiang1
    var t_name = options.t_name
    if (openid == options.f_id) {
      var is_img = options.is_img
    } else {
      var is_img = options.is_img
    }
    a.util.request({
      'url': 'entry/wxapp/url',
      success: function(res) {
        that.setData({
          url: res.data
        })
      }
    })
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          scroll_height: res.windowHeight
        })
      },
    })
    wx.getRecorderManager && (s.onStart(function() {
      console.log("recorder start"), that.setData({
        record_text: "松开 结束"
      }), that.data.flagBoo && s.stop();
    }), s.onStop(function(t) {
      console.log("recorder stop", t);
      var e = t.tempFilePath,
        o = (t.duration / 1e3).toFixed();
      if (o <= 0) return wx.showToast({
        title: "太短了",
        icon: "none",
        duration: 500
      }), void that.setData({
        record_text: "按住 说话"
      });
      that.setData({
          time: o,
          width: 50 + 400 * o / 60,
          record_text: "按住 说话",
          RecordFlag: !0,
          tempFilePath: e
        }), console.log(e),
        a.util.request({
          'url': 'entry/wxapp/url',
          success: function(res) {
            var url = res.data
            wx.uploadFile({
              url: url + 'app/index.php?i=' + uniacid + '&c=entry&a=wxapp&do=uploadevideo&m=hyb_yl',
              filePath: e,
              name: "upfile",
              success: function(t) {
                console.log(t.data)
                a.util.request({
                  'url': 'entry/wxapp/SaveChatMsg',
                  'data': {
                    openid: wx.getStorageSync('openid'),
                    fid: options.f_id,
                    tid: options.t_id,
                    t_msg: t.data,
                    f_name: that.data.f_name,
                    nickName: that.data.t_name,
                    touxiang: that.data.touxiang1,
                    is_img: that.data.is_img,
                    docid: options.docid,
                    typetext: 3,
                  },
                  success: function(res) {
                    console.log(res)
                    //wx.hideLoading()
                  },
                })
                var ss = that.data.centendata;
                var date = new Date();
                var time = util.formatTime(date);
                var data = {
                  is_show_right: 1,
                  typetext: 3,
                  msg: t.data,
                  // msg: "7185805444885345.mp3",
                  playFlag: false,
                  duration: time
                }
                ss.push(data);
                that.setData({
                  centendata: ss,
                  ymurl: url + "attachment/"
                })
              }
            });

          },
        })

    })), wx.createInnerAudioContext && (n.onPlay(function() {
      console.log("开始播放"), that.data.oppositeList[that.data.playIndex] && (that.data.oppositeList[that.data.playIndex].playFlag = !0,
        that.setData({
          oppositeList: that.data.oppositeList
        }));
    }), n.onError(function(t) {
      console.log(t.errMsg), console.log(t.errCode);
    }), n.onStop(function() {
      console.log("停止播放");
    }), n.onEnded(function() {
      console.log("播放完毕了"), that.data.oppositeList[that.data.playIndex] && (that.data.oppositeList[that.data.playIndex].playFlag = !1,
        that.setData({
          oppositeList: that.data.oppositeList
        }));
    }));
    that.setData({
        docid: options.docid,
        f_id: options.f_id,
        m_id: options.u_id,
        t_id: options.t_id,
        avatarUrl: userInfo.avatarUrl,
        f_name: options.name,
        is_img: options.docimg,
        touxiang: options.touxiang,
        uniacid: uniacid,
        touxiang1: touxiang1,
        t_name: t_name
      }),
      this.getUserinfo(options.t_id)

    //修改已读信息
    a.util.request({
      'url': 'entry/wxapp/ReadMsg',
      'data': {
        openid: wx.getStorageSync('openid'),
        fid: that.data.f_id,
        tid: that.data.t_id,
        ifkf: 0
      },
      success: function(res) {
        console.log(res)
        that.setData({
          centendata: res.data.data.chat_list,
        })
        that.bottom();
      },
    })
    this.getKfuid()
    //循环查询对方发送的消息 把最新的消息显示出来 计时器6秒执行一次
    var if_over = wx.getStorageSync('huihuaover')
    if (if_over !== 1 || if_over !== '') {
      var setintervalFunction = setInterval(function() {
        a.util.request({
          'url': 'entry/wxapp/ReadMsg',
          'data': {
            openid: wx.getStorageSync('openid'),
            fid: that.data.f_id,
            tid: that.data.t_id,
            ifkf: 0
          },
          success: function(res) {
            that.setData({
              centendata: res.data.data.chat_list,
              open: false
            })
          },
        })
        wx.hideNavigationBarLoading()
        that.bottom();

      }, 6000) //6秒查询一次
      that.setData({
        setinterval: setintervalFunction
      })
    }

  },
  toPlay: function(e) {
    var t = this,
      src = e.currentTarget.dataset.src,
      index = e.currentTarget.dataset.index,
      ss = t.data.centendata,
      url = t.data.url + 'attachment/';
    ss[index].playFlag = true;
    console.log(url + src)
    wx.playBackgroundAudio({
      dataUrl: url + src,
    })
    t.setData({
      centendata: ss
    })
  },
  goText: function(e) {
    var that = this
    var if_over = that.data.if_over
    if (if_over == 1) {
      wx.showToast({
        title: '当前会话已结束',
        icon: 'none',
        duration: 2e3
      })
    } else {
      this.setData({
        recordFlag: !1,
      });
    }
  },
  sendRecord: function() {
    var t = this,
      e = t.data.oppositeList,
      o = new Date().getTime(),
      s = {
        version: 1,
        operation: 5,
        seqId: o,
        data: {
          to: t.data.patientId,
          from: t.data.doctorId,
          ctime: o,
          msgType: "SINGLE_VIDEO",
          content: t.data.videoPath,
          sessionId: t.data.sessionId,
          role: t.data.role,
          duration: parseInt(t.data.time)
        }
      },
      i = JSON.stringify(s);
    wx.sendSocketMessage({
      data: i,
      success: function(t) {}
    }), e.push({
      from: t.data.doctorId,
      msgType: "SINGLE_VIDEO",
      content: t.data.video,
      // ctime: a.toDate(o),
      seqId: o,
      duration: parseInt(t.data.time)
    }), wx.removeStorageSync("contentText"), t.setData({
      oppositeList: e,
      scrollTop: t.data.scrollTop + 1e3
    });
  },
  onShow: function() {
    var t = this;
    o = 0, wx.getStorageSync("contentText") && this.setData({
      imgBoo: !1,
      heightFlag: !0,
      recordFlag: !1
    }), wx.getSetting({
      success: function(e) {
        console.log(e), 0 == e.authSetting["scope.record"] && t.setData({
          recordBoo: !0
        }), null == e.authSetting["scope.record"] && t.setData({
          recordBooTwo: !0
        }), e.authSetting["scope.record"] && t.setData({
          recordBoo: !1
        });
      }
    });
  },
  onUnload: function() {

    clearInterval(this.data.setinterval)
  },
  scrolltoupper: function() {
    var t = this;
    this.data.currentResult <= 0 || e.default.scrolltoupper(t);
  },

  heartbeat: function() {
    var t = {
        version: 1,
        operation: 3,
        seqId: new Date().getTime(),
        data: {}
      },
      e = JSON.stringify(t);
    wx.sendSocketMessage({
      data: e,
      success: function(t) {}
    });
  },
  pullMsg: function(t, e, a) {
    console.log(a.data.sessionId);
    var o = {
        version: 1,
        operation: 11,
        seqId: new Date().getTime(),
        data: {
          userId: a.data.userId,
          offset: t,
          limit: e,
          sessionId: a.data.sessionId,
          medType: a.data.signType
        }
      },
      s = JSON.stringify(o);
    wx.sendSocketMessage({
      data: s,
      success: function(t) {}
    });
  },
  toast: function() {
    if (this.data.disableFlag) return console.log(22222), void wx.showToast({
      title: "对方已结束本次咨询",
      icon: "none",
      duration: 2e3
    });
  },
  getText: function(e) {
    var that = this
    this.setData({
      news_input_val: e.detail.value
    })
    var if_over = that.data.if_over
    if_over == 1 ? wx.showToast({
      title: "咨询已结束",
      icon: "none",
      duration: 2e3
    }) : 0 != e.detail.value.replace(/(^\s*)|(\s*$)/g, "").length ? this.setData({
      imgBoo: !1
    }) : this.setData({
      imgBoo: !0
    });
  },
  sendChooseImg: function() {
    var a = this,
      e = a.data.tempFilePaths;
    var uniacid = a.data.uniacid
    var if_over = a.data.if_over
    if (if_over == 1) {
      wx.showToast({
        title: '当前会话已结束',
        icon: 'none',
        duration: 2e3
      })
    } else {
      wx.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: function(t) {
          console.log(t.tempFilePaths)
          wx.uploadFile({
            url: a.data.url + 'app/index.php?i=' + uniacid + '&c=entry&a=wxapp&do=Uploadsarray&m=hyb_yl',
            filePath: t.tempFilePaths[0],
            name: 'upfile',
            formData: {
              'path': 'wxchat'
            },
            success: function(res) {
              console.log(res.data)
              a.setData({
                uplogo: res.data,
                imgBoo: !1
              })
            },
            fail: function(res) {
              console.log(res)
            },
          })
          a.setData({
            tempFilePaths: t.tempFilePaths[0]
          });
        }
      });
    }

  },

  closeBtn: function() {
    var e = this;
    var m_id = e.data.m_id
    wx.showModal({
      title: "确定要结束咨询吗？",
      confirmColor: "#3b4ca9",
      success: function(res) {
        if (res.confirm) {
          //结束咨询
          a.util.request({
            'url': 'entry/wxapp/Jieshuzix',
            data: {
              m_id: m_id
            },
            success: function(res) {
              if (res.data == 1) {
                wx.showToast({
                  title: '会话结束成功',
                  icon: 'none',
                  duration: 2e3,
                  success: function() {
                    setTimeout(function() {
                      wx.navigateBack({
                        delta: 1
                      })
                    }, 2000)
                  }
                })
              } else {
                wx.showToast({
                  title: '当前会话已结束',
                  icon: 'none',
                  duration: 2e3
                })
              }

            }
          })
        }

      }
    });
  },
  backout: function(t) {
    var e = this,
      a = t.target.dataset.backmsg,
      o = this.data.seqIdArr.indexOf(a),
      s = t.target.dataset.index;
    var i = new Date().getTime();
    console.log(i - o), console.log(t), e.data.backoutFlag = !1, wx.showActionSheet({
      itemList: ["撤回"],
      success: function(t) {
        if (console.log(t.tapIndex), e.data.backoutFlag = !0, 0 == t.tapIndex) {
          if (i - e.data.seqIdArr[o] > 12e4 || -1 == o) return void wx.showToast({
            title: "超过2分钟不能撤回哦",
            icon: "none",
            duration: 2e3
          });
          console.log(e.data.role);
          var a = {
              version: 1,
              operation: 15,
              seqId: new Date().getTime(),
              data: {
                sessionId: e.data.sessionId,
                to: e.data.patientId,
                from: e.data.doctorId,
                msgType: "SINGLE_IMAGE",
                msgId: e.data.msgIdArr[o],
                role: e.data.role
              }
            },
            n = JSON.stringify(a);
          wx.sendSocketMessage({
            data: n,
            success: function(t) {
              var a = e.data.oppositeList;
              a.splice(s, 1), e.setData({
                oppositeList: a
              });
            }
          });
        }
      },
      fail: function(t) {
        console.log(t), e.data.backoutFlag = !0;
      }
    });
  },
  getUserinfo: function(t_id) {
    var that = this
    a.util.request({
      'url': 'entry/wxapp/Binrinfo',
      data: {
        openid: t_id
      },
      success: function(res) {
        console.log(res)
        var if_over = res.data.if_over
        if (res.data.if_over == 1) {
          wx.setStorageSync('huihuaover', if_over)
        }
        that.setData({
          t_msg: res.data,
          if_over: res.data.if_over
        })
      }
    })
  },
  add: function(e) {
    var that = this
    var date = new Date();
    var time = util.formatTime(date);
    var form_id = e.detail.formId
    var f_name = that.data.f_name
    var nickName = that.data.t_name
    var touxiang = that.data.avatarUrl
    var docid = that.data.docid
    var is_img = that.data.is_img
    var openid = wx.getStorageSync('openid')
    var data_arr = that.data.uplogo;
    if (this.data.tempFilePaths == "" && that.data.news_input_val == "") {
      wx.showModal({
        title: '提示',
        content: '输入消息不能为空',
      })
    } else {
      if (this.data.tempFilePaths !== "" && that.data.news_input_val == "") {
        var typetext = 1
      } else if (this.data.tempFilePaths !== "" && that.data.news_input_val !== "") {
        var typetext = 2
      } else {
        var typetext = 0
      }


      // console.log(that.data.f_name)
      // console.log(nickName)
      // console.log(touxiang)
      // console.log(that.data.is_img)
      // console.log(that.data.docid)
      // console.log(that.data.t_id)
      // console.log(that.data.f_id)
      a.util.request({
        'url': 'entry/wxapp/UserFormId',
        'data': {
          form_id: form_id,
          openid: openid
        },
        success: function(res) {
          a.util.request({
            'url': 'entry/wxapp/SaveChatMsg',
            'data': {
              openid: wx.getStorageSync('openid'),
              fid: that.data.f_id,
              tid: that.data.t_id,
              t_msg: that.data.news_input_val,
              data_arr: data_arr,
              f_name: that.data.f_name,
              nickName: nickName,
              touxiang: touxiang,
              is_img: is_img,
              docid: docid,
              typetext: typetext,
              kfid: that.data.kfid,
              ifkf: 0
            },
            success: function(res) {

              console.log(res)
              if (res) {
                var centendata = that.data.centendata
                centendata.push({
                  time: time,
                  is_show_right: 1,
                  is_img: is_img,
                  show_rignt: true,
                  content: that.data.news_input_val,
                  typetext: 0
                })
                that.setData({
                  centendata: centendata,
                  news_input_val: "",
                  imgBoo: !0,
                  tempFilePaths: "",
                  open: false
                })
                // that.bottom()
              }
              wx.hideLoading()
            },
          })
        },
      })
    }
  },
  //查询一条客服id
  getKfuid: function() {
    var that = this
    a.util.request({
      'url': 'entry/wxapp/Kfuid',
      success: function(res) {
        that.setData({
          kfid: res.data.zid
        })
      }
    })
  }
})
var s = wx.getRecorderManager ? wx.getRecorderManager() : null,
  i = {
    duration: 6e4,
    sampleRate: 44100,
    numberOfChannels: 1,
    encodeBitRate: 192e3,
    format: "mp3",
    frameSize: 50
  },
  n = wx.createInnerAudioContext ? wx.createInnerAudioContext() : null;